package com.avic.rong.richEditor;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.activity.login.LoginPhoneActivity;
import com.avic.rong.activity.mine.MyReleaseActivity;
import com.avic.rong.richEditor.api.ContentPublishApi;
import com.avic.rong.richEditor.fragment.EditorMenuFragment;
import com.avic.rong.richEditor.interfaces.OnActionPerformListener;
import com.avic.rong.richEditor.keyboard.KeyboardHeightObserver;
import com.avic.rong.richEditor.keyboard.KeyboardHeightProvider;
import com.avic.rong.richEditor.keyboard.KeyboardUtils;
import com.avic.rong.richEditor.util.FileIOUtil;
import com.avic.rong.richEditor.widget.SuperLinkDialog;
import com.avic.rong.richEditor.widget.TableArgumentDialog;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.customWedgit.SheetDialog;
import com.even.mricheditor.ActionType;
import com.even.mricheditor.RichEditorAction;
import com.even.mricheditor.RichEditorCallback;
import com.even.mricheditor.ui.ActionImageView;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;
import com.example.minato.minastore.utils.CircleProgressDialog;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 发布文章
 */
@SuppressLint("SetJavaScriptEnabled")
public class RichEditorActivity extends BaseActivity implements KeyboardHeightObserver {

    public static final Integer CODE_PUBLISH = 100;

    @BindView(R.id.wv_container)
    WebView mWebView;
    @BindView(R.id.fl_action)
    FrameLayout flAction;
    @BindView(R.id.ll_action_bar_container)
    LinearLayout llActionBarContainer;
    @BindView(R.id.img_cover)
    ImageView img_cover;//蒙层

    /**
     * The keyboard height provider
     */
    private KeyboardHeightProvider keyboardHeightProvider;
    private boolean isKeyboardShowing;
    private String htmlContent = "<p>请输入内容...</p>";

    private RichEditorAction mRichEditorAction;
    private RichEditorCallback mRichEditorCallback;

    private EditorMenuFragment mEditorMenuFragment;

    private SheetDialog sheetDialog;
    private String contentString = "";
    private String titleString = "";
    private CircleProgressDialog circleProgressDialog;
    private int status = 3;//0:草稿 1:发布 3:审核中 4:拒绝 5:用户草稿
    private boolean clickBack = false;//控制回退按钮

    private List<ActionType> mActionTypeList =
            Arrays.asList(ActionType.BOLD, ActionType.ITALIC, ActionType.UNDERLINE,
                    ActionType.STRIKETHROUGH, ActionType.SUBSCRIPT, ActionType.SUPERSCRIPT,
                    ActionType.NORMAL, ActionType.H1, ActionType.H2, ActionType.H3, ActionType.H4,
                    ActionType.H5, ActionType.H6, ActionType.INDENT, ActionType.OUTDENT,
                    ActionType.JUSTIFY_LEFT, ActionType.JUSTIFY_CENTER, ActionType.JUSTIFY_RIGHT,
                    ActionType.JUSTIFY_FULL, ActionType.ORDERED, ActionType.UNORDERED, ActionType.LINE,
                    ActionType.BLOCK_CODE, ActionType.BLOCK_QUOTE, ActionType.CODE_VIEW);

    private List<Integer> mActionTypeIconList =
            Arrays.asList(R.drawable.ic_format_bold, R.drawable.ic_format_italic,
                    R.drawable.ic_format_underlined, R.drawable.ic_format_strikethrough,
                    R.drawable.ic_format_subscript, R.drawable.ic_format_superscript,
                    R.drawable.ic_format_para, R.drawable.ic_format_h1, R.drawable.ic_format_h2,
                    R.drawable.ic_format_h3, R.drawable.ic_format_h4, R.drawable.ic_format_h5,
                    R.drawable.ic_format_h6, R.drawable.ic_format_indent_decrease,
                    R.drawable.ic_format_indent_increase, R.drawable.ic_format_align_left,
                    R.drawable.ic_format_align_center, R.drawable.ic_format_align_right,
                    R.drawable.ic_format_align_justify, R.drawable.ic_format_list_numbered,
                    R.drawable.ic_format_list_bulleted, R.drawable.ic_line, R.drawable.ic_code_block,
                    R.drawable.ic_format_quote, R.drawable.ic_code_review);

    private static final int REQUEST_CODE_CHOOSE = 0;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_rich_editor;
    }


    @Override
    public void initView() {

        ButterKnife.bind(this);


        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                Logger.i("----------------------shouldOverrideUrlLoading-");
                return true;
            }
        });

        mWebView.setWebChromeClient(new CustomWebChromeClient());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
//        mWebView.getSettings().setAppCacheEnabled(false);
        mRichEditorCallback = new MRichEditorCallback();
        mWebView.addJavascriptInterface(mRichEditorCallback, "MRichEditor");
        mWebView.loadUrl("file:///android_asset/richEditor.html");
        mRichEditorAction = new RichEditorAction(mWebView);

        keyboardHeightProvider = new KeyboardHeightProvider(this);
        findViewById(R.id.fl_container).post(new Runnable() {
            @Override
            public void run() {
                keyboardHeightProvider.start();
            }
        });

        //蒙层处理
        if (SharedPreferencesUtil.getInstance().getAsBoolean(ConstantsUtils.COVER_CONTENT_PUBLISH_FIRST, false)) {
            img_cover.setVisibility(View.GONE);
        } else {
            img_cover.setVisibility(View.VISIBLE);
        }


        int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
        int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 9, getResources().getDisplayMetrics());

//        for (int i = 0, size = mActionTypeList.size(); i < size; i++) {
//            final ActionImageView actionImageView = new ActionImageView(this);
//            actionImageView.setLayoutParams(new LinearLayout.LayoutParams(width, width));
//            actionImageView.setPadding(padding, padding, padding, padding);
//            actionImageView.setActionType(mActionTypeList.get(i));
//            actionImageView.setTag(mActionTypeList.get(i));
//            actionImageView.setActivatedColor(R.color.colorAccent);
//            actionImageView.setDeactivatedColor(R.color.tintColor);
//            actionImageView.setRichEditorAction(mRichEditorAction);
//            actionImageView.setBackgroundResource(R.drawable.btn_colored_material);
//            actionImageView.setImageResource(mActionTypeIconList.get(i));
//            actionImageView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    actionImageView.command();
//                }
//            });
//            llActionBarContainer.addView(actionImageView);
//        }

        //软键盘区域快捷menu
        mEditorMenuFragment = new EditorMenuFragment();
        mEditorMenuFragment.setActionClickListener(new MOnActionPerformListener(mRichEditorAction));
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction()
                .add(R.id.fl_action, mEditorMenuFragment, EditorMenuFragment.class.getName())
                .commit();

    }

    @Override
    protected void addListener() {

    }

    private class CustomWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {
                if (!TextUtils.isEmpty(htmlContent)) {
                    //初始化的placeholder
//                    mRichEditorAction.insertHtml(htmlContent);
                }
                KeyboardUtils.showSoftInput(RichEditorActivity.this);
                Logger.i("--------------------onProgressChanged");
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }
    }

    //左下角控制按钮
    @OnClick(R.id.iv_action)
    void onClickAction() {
        if (flAction.getVisibility() == View.VISIBLE) {
            flAction.setVisibility(View.GONE);
        } else {
            if (isKeyboardShowing) {
                KeyboardUtils.hideSoftInput(RichEditorActivity.this);
            }
            flAction.setVisibility(View.VISIBLE);
        }
    }

    private boolean contentHave = false;
    private boolean titleHave = false;
    private RichEditorCallback.OnGetHtmlListener onGetHtmlListener = new RichEditorCallback.OnGetHtmlListener() {
        @Override
        public void getHtml(String html) {
            if (!clickBack) {//如果非按回退按钮
//                if (TextUtils.isEmpty(html) || "<p><br></p>".equals(html)) {
//                    ToastTools.showToast("正文不能为空!");
//                    return;
//                }else{
//                    contentHave = true;
//                }
            }
            contentString = html;

            if (TextUtils.isEmpty(html) || "<p><br></p>".equals(html)) {
                contentHave = false;
                if (status == 3 && clickFaBu){//发布的时候验证
                    ToastTools.showToast("正文不能为空!");
//                    Toast toast = Toast.makeText(RichEditorActivity.this,"正文不能为空!",Toast.LENGTH_SHORT);
//                    toast.setGravity(Gravity.CENTER, 0, 0);
//                    toast.show();
                    return;
                }
            }else{
                contentHave = true;
            }

            handler.sendEmptyMessage(1);
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                mRichEditorAction.getTitle(new RichEditorAction.TitleCallBackInterface() {
                    @Override
                    public void calBack(String title) {
                        titleString = title;
                        if (!clickBack) {//没按回退按钮
                            if (TextUtils.isEmpty(titleString) || ConstantsUtils.EMPTY_STR_DOUBLE_QUOTE.equals(titleString)) {
//                                ToastTools.showToast("标题不能为空!");
                                titleString = "文章标题应为5~30字";
//                                if (contentHave){
//                                    titleHave = true;
//                                }else{
//                                    titleHave = false;
//                                }
//                               return;
                            }
                            if ((titleString.length() < 5 || titleString.length() > 30) && !"文章标题应为5~30字".equals(titleString)) {
                                ToastTools.showToast("文章标题应为5~30字");
                                return;
                            }
                            if ("文章标题应为5~30字".equals(titleString)){
                                if (status == 3 && clickFaBu){
                                    ToastTools.showToast("标题或内容不能为空!");
//                                    Toast toast = Toast.makeText(RichEditorActivity.this,"标题或内容不能为空!",Toast.LENGTH_SHORT);
//                                    toast.setGravity(Gravity.CENTER, 0, 0);
//                                    toast.show();
                                    return;
                                }
                                if (!contentHave){
                                    ToastTools.showToast("标题或内容不能为空!");
                                    return;
                                }
                            }else{
                                titleHave = true;
                            }

                            if (!SharedPreferencesUtil.isLogin()){
                                startActivity(LoginPhoneActivity.getIntent(RichEditorActivity.this,"RichEditorActivity"));
                            }else{
                                ContentPublishApi contentPublishApi = new ContentPublishApi(RichEditorActivity.this, contentListener);
                                Logger.i("----" + SharedPreferencesUtil.getLoginToken());
                                contentPublishApi.setArg(SharedPreferencesUtil.getLoginToken(), contentString, titleString, 4, status);
                                circleProgressDialog = new CircleProgressDialog(RichEditorActivity.this);
                                circleProgressDialog.show();
                                HttpManager.getInstance().doHttpDeal(contentPublishApi);
                            }

                        } else {

//                            if ((TextUtils.isEmpty(contentString) || "<p><br></p>".equals(contentString)) && (TextUtils.isEmpty(titleString) || ConstantsUtils.EMPTY_STR_DOUBLE_QUOTE.equals(titleString))) {
//                                if (!(TextUtils.isEmpty(titleString) || ConstantsUtils.EMPTY_STR_DOUBLE_QUOTE.equals(titleString)) && (titleString.length() < 5 || titleString.length() > 30)) {
//                                    ToastTools.showToast("文章标题应为5~30字");
//
////                                    return;
//                                } else {
//                                    finish();
//                                }
//                            } else {
//                                backTip();
//                            }

//                            if (TextUtils.isEmpty(titleString) || ConstantsUtils.EMPTY_STR_DOUBLE_QUOTE.equals(titleString)){
//                                titleString = "文章标题应为5~30字";
//                            }
                            if ((TextUtils.isEmpty(contentString) || "<p><br></p>".equals(contentString)) && (TextUtils.isEmpty(titleString) || ConstantsUtils.EMPTY_STR_DOUBLE_QUOTE.equals(titleString))) {
                                finish();
                            }else{
                                backTip();
                            }

                            clickBack = false;
                        }
                    }
                });

            }
        }
    };

    //获取标准数据监听
    HttpOnNextListener<BaseResultEntity> contentListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (circleProgressDialog != null) {
                circleProgressDialog.dismiss();
            }
            if (!ConstantsUtils.STATUS_SUCCESS_200.equals(subjects.getCode())) {
                ToastTools.showToast(RichEditorActivity.this, subjects.getMsg());
                return;
            }

            KeyboardUtils.hideSoftInput(RichEditorActivity.this);

//            Toast toast = Toast.makeText(RichEditorActivity.this,"已提交审核，审核通过后发布", Toast.LENGTH_SHORT);
//            toast.setGravity(Gravity.CENTER, 0, 0);
//            toast.show();
            if (status == 5){
                ToastTools.showToast("草稿保存成功!");
            }else{
                ToastTools.showToast("已提交审核，审核通过后发布");
            }

            startActivity(MyReleaseActivity.queryIntent(RichEditorActivity.this));
            finish();
//            PublishTipDialog publishTipDialog = new PublishTipDialog(RichEditorActivity.this);
//            publishTipDialog.setCallBackInterface(new PublishTipDialog.CallBackInterface() {
//                @Override
//                public void cannel() {
//                    finish();
//                }
//            });
//            publishTipDialog.show();
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            if (circleProgressDialog != null) {
                circleProgressDialog.dismiss();
            }
        }
    };


    boolean clickFaBu = false;
    //发布
    @OnClick(R.id.iv_get_html)
    void onClickGetHtml() {
        clickFaBu = true;
        status = 3;//发布
        clickBack = false;
        if (SharedPreferencesUtil.isLogin()){
            mRichEditorAction.refreshHtml(mRichEditorCallback, onGetHtmlListener);
        }else{
            startActivityForResult(LoginPhoneActivity.queryIntent(RichEditorActivity.this), CODE_PUBLISH);
        }
    }

    @OnClick(R.id.iv_action_undo)
    void onClickUndo() {
        mRichEditorAction.undo();
    }

    @OnClick(R.id.iv_action_redo)
    void onClickRedo() {
        mRichEditorAction.redo();
    }

    @OnClick(R.id.iv_action_txt_color)
    void onClickTextColor() {
        mRichEditorAction.foreColor("blue");
    }

    @OnClick(R.id.iv_action_txt_bg_color)
    void onClickHighlight() {
        mRichEditorAction.backColor("red");
    }

    @OnClick(R.id.iv_action_line_height)
    void onClickLineHeight() {
        mRichEditorAction.lineHeight(20);
    }

    //插入图片
    @OnClick(R.id.iv_action_insert_image)
    void onClickInsertImage() {
        KeyboardUtils.hideSoftInput(RichEditorActivity.this);

        PictureSelector.create((Activity) this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
//                    .maxSelectNum(3)
                .maxSelectNum(1)
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(3)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(false)// 是否显示拍照按钮
                .isZoomAnim(false)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .glideOverride(260, 260)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PictureConfig.CHOOSE_REQUEST) {//选择照片

            // 图片选择结果回调
            List<LocalMedia> tempList = PictureSelector.obtainMultipleResult(data);
            for (LocalMedia media : tempList) {
                Logger.i("图片-----》", media.getCompressPath());

                //1.Insert the Base64 String (Base64.NO_WRAP)
////                ImageItem imageItem = images.get(0);
////                mRichEditorAction.insertImageData(imageItem.name,
////                        encodeFileToBase64Binary(imageItem.path));

                upLoad(media.getCompressPath());
//                String picName = media.getPath().substring(media.getPath().lastIndexOf("/"));
//                mRichEditorAction.insertImageData(picName, encodeFileToBase64Binary(media.getCompressPath()));

//                mRichEditorAction.insertImageUrl("http://image.rongrong.cn/group1/M00/02/97/CgMDF1vjkPKAdi-TAABnD54LzC8851.jpg");
            }
        }else if(requestCode == CODE_PUBLISH){//登录后发布
            mRichEditorAction.refreshHtml(mRichEditorCallback, onGetHtmlListener);
        }
    }

    private static String encodeFileToBase64Binary(String filePath) {
        byte[] bytes = FileIOUtil.readFile2BytesByStream(filePath);
        byte[] encoded = Base64.encode(bytes, Base64.NO_WRAP);
        return new String(encoded);
    }

    //插入超链接
    @OnClick(R.id.iv_action_insert_link)
    void onClickInsertLink() {
        KeyboardUtils.hideSoftInput(RichEditorActivity.this);

        SuperLinkDialog superLinkDialog = new SuperLinkDialog(RichEditorActivity.this);
        superLinkDialog.setLinkCallBackInterface(new SuperLinkDialog.LinkCallBackInterface() {
            @Override
            public void callBack(String linkName, String linkAddress) {
                mRichEditorAction.createLink(linkName, linkAddress);
            }
        });
        superLinkDialog.show();
    }


    //插入表格
    @OnClick(R.id.iv_action_table)
    void onClickInsertTable() {
        KeyboardUtils.hideSoftInput(RichEditorActivity.this);


        TableArgumentDialog tableArgumentDialog = new TableArgumentDialog(RichEditorActivity.this);
        tableArgumentDialog.setTableBackInterface(new TableArgumentDialog.TableBackInterface() {
            @Override
            public void callBack(int rows, int cols) {
                mRichEditorAction.insertTable(rows, cols);
            }
        });
        tableArgumentDialog.show();

    }

    //取消
    @OnClick(R.id.tv_cancel)
    public void backDirct(View view) {
        clickFaBu = false;
        KeyboardUtils.hideSoftInput(RichEditorActivity.this);
        onBackPressed();
    }

    @Override
    public void onResume() {
        super.onResume();
        keyboardHeightProvider.setKeyboardHeightObserver(this);
//        flAction.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                KeyboardUtils.showSoftInput(RichEditorActivity.this);
//            }
//        },200);

    }


    @Override
    public void onPause() {
        super.onPause();
        keyboardHeightProvider.setKeyboardHeightObserver(null);
        if (flAction.getVisibility() == View.INVISIBLE) {
            flAction.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        keyboardHeightProvider.close();
    }


    //键盘监听
    @Override
    public void onKeyboardHeightChanged(int height, int orientation) {
        isKeyboardShowing = height > 0;
        Logger.i("---------------------onKeyboardHeightChanged:" + height + "-----orientation:" + orientation + "--" + (flAction.getVisibility() != View.VISIBLE));
        if (height != 0) {
            flAction.setVisibility(View.INVISIBLE);
            ViewGroup.LayoutParams params = flAction.getLayoutParams();

            if (height < 0) {
                height = 0;
            }
            params.height = height;
            if (Build.MODEL.equalsIgnoreCase("MI 8")){//小米 8的bug
                params.height = height +  90;
            }

            flAction.setLayoutParams(params);

            Logger.i("---------------------onKeyboardHeightChanged:111" + height + "-----orientation:" + orientation + "--" + (flAction.getVisibility() != View.VISIBLE));

//            performInputSpaceAndDel();
        } else if (flAction.getVisibility() != View.VISIBLE) {
            Logger.i("---------------------onKeyboardHeightChanged:222" + height + "-----orientation:" + orientation + "--" + (flAction.getVisibility() != View.VISIBLE));
            flAction.setVisibility(View.GONE);

            if (Build.MODEL.equalsIgnoreCase("MI 8")){//小米 8的bug
                ViewGroup.LayoutParams params = flAction.getLayoutParams();
                params.height = 0;
                flAction.setLayoutParams(params);
            }
        }
    }

    //TODO not a good solution
    private void performInputSpaceAndDel() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                    Instrumentation instrumentation = new Instrumentation();
                    instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_SPACE);
                    instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DEL);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    class MRichEditorCallback extends RichEditorCallback {

        @Override
        public void notifyFontStyleChange(ActionType type, final String value) {
            ActionImageView actionImageView = (ActionImageView) llActionBarContainer.findViewWithTag(type);
            if (actionImageView != null) {
                actionImageView.notifyFontStyleChange(type, value);
            }

            if (mEditorMenuFragment != null) {
                mEditorMenuFragment.updateActionStates(type, value);
            }
        }
    }

    public class MOnActionPerformListener implements OnActionPerformListener {
        private RichEditorAction mRichEditorAction;

        public MOnActionPerformListener(RichEditorAction mRichEditorAction) {
            this.mRichEditorAction = mRichEditorAction;
        }

        @Override
        public void onActionPerform(ActionType type, Object... values) {
            if (mRichEditorAction == null) {
                return;
            }

            String value = null;
            if (values != null && values.length > 0) {
                value = (String) values[0];
            }

            switch (type) {
                case SIZE:
                    mRichEditorAction.fontSize(Double.valueOf(value));
                    break;
                case LINE_HEIGHT:
                    mRichEditorAction.lineHeight(Double.valueOf(value));
                    break;
                case FORE_COLOR:
                    mRichEditorAction.foreColor(value);
                    break;
                case BACK_COLOR:
                    mRichEditorAction.backColor(value);
                    break;
                case FAMILY:
                    mRichEditorAction.fontName(value);
                    break;
                case IMAGE:
                    onClickInsertImage();
                    break;
                case LINK:
                    onClickInsertLink();
                    break;
                case TABLE:
                    onClickInsertTable();
                    break;
                case BOLD:
                case ITALIC:
                case UNDERLINE:
                case SUBSCRIPT:
                case SUPERSCRIPT:
                case STRIKETHROUGH:
                case JUSTIFY_LEFT:
                case JUSTIFY_CENTER:
                case JUSTIFY_RIGHT:
                case JUSTIFY_FULL:
                case CODE_VIEW:
                case ORDERED:
                case UNORDERED:
                case INDENT:
                case OUTDENT:
                case BLOCK_QUOTE:
                case BLOCK_CODE:
                case NORMAL:
                case H1:
                case H2:
                case H3:
                case H4:
                case H5:
                case H6:
                case LINE:
                    ActionImageView actionImageView = (ActionImageView) llActionBarContainer.findViewWithTag(type);
                    if (actionImageView != null) {
                        actionImageView.performClick();
                    }
                    break;
                default:
                    break;
            }
        }
    }


    //隐藏蒙层
    @OnClick(R.id.img_cover)
    public void hideCover(View view) {
        SharedPreferencesUtil.getInstance().put(ConstantsUtils.COVER_CONTENT_PUBLISH_FIRST, true);
        img_cover.setVisibility(View.GONE);
    }


    @Override
    public void onBackPressed() {
        clickFaBu = false;
        clickBack = true;
        mRichEditorAction.refreshHtml(mRichEditorCallback, onGetHtmlListener);
    }


    private void backTip() {
        sheetDialog = new SheetDialog.Builder(RichEditorActivity.this).setTitle(ConstantsUtils.EMPTY_STR)
                .addMenu("放弃编辑", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (sheetDialog != null && sheetDialog.isShowing()) {
                            sheetDialog.dismiss();
                        }
                        finish();
                    }
                })
                .addMenu("保存草稿并退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (sheetDialog != null && sheetDialog.isShowing()) {
                            sheetDialog.dismiss();
                        }
                        status = 5;//用户草稿
                        clickBack = false;
                        mRichEditorAction.refreshHtml(mRichEditorCallback, onGetHtmlListener);
//                        ContentPublishApi contentPublishApi = new ContentPublishApi(RichEditorActivity.this, contentListener);
//                        contentPublishApi.setArg(SharedPreferencesUtil.getLoginToken(), contentString, titleString, 4, status);
//                        circleProgressDialog = new CircleProgressDialog(RichEditorActivity.this);
//                        HttpManager.getInstance().doHttpDeal(contentPublishApi);
                    }
                })
                .setCancelListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sheetDialog.dismiss();
                    }
                }).create();
        sheetDialog.show();
    }


    /*
     * 上传图片
     * */
    public void upLoad(String photoPath) {

        circleProgressDialog = new  CircleProgressDialog(RichEditorActivity.this);
        if (!circleProgressDialog.isShowing()){
            circleProgressDialog.show();
        }


        File file = new File(photoPath);
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody fileBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), requestBody)
                .build();

        Request request = new Request.Builder()
                .url(AppUtils.BASE_URL + "uuuuu/upload")
                .post(fileBody)
                .build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logger.e("OwnMessageActivity", "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (circleProgressDialog != null && circleProgressDialog.isShowing()){
                    circleProgressDialog.dismiss();
                }

                String string = response.body().string();
                Gson gson = new Gson();
                final BaseResultEntity baseResultEntity = gson.fromJson(string, BaseResultEntity.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                            String imgUrl = (String) baseResultEntity.getData();
                            Logger.i("----------------------img：" + imgUrl);
                            mRichEditorAction.insertImageUrl(imgUrl);
                        } else {
                            Toast toast = Toast.makeText(RichEditorActivity.this, "图片保存失败", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                        }
                    }
                });
            }
        });
    }


}

























